import { Panel } from 'comps/common';
import { Select, Button, Form, Popconfirm, message } from 'antd';

const FormItem = Form.Item;

// TODO 两个更新动作的按钮 fetching

let TeamForm = ({ companyTeams, groupId, teamId, form, onAssign }) => {
  const { getFieldProps, getFieldValue } = form;

  const onSubmit = () => {
    onAssign(groupId, getFieldValue('teamId'))
      .then(({ error }) => {
        if (!error) {
          message.success('更新成功');
        }
      });
  };

  return (
    <Form inline className='team-form' form={form} onSubmit={onSubmit}>
      <FormItem label='负责开发组：'>
        <Select style={{ width: '200px' }} {...getFieldProps('teamId', { initialValue: teamId })}>
          {companyTeams.map((team) => <Option key={team.id} value={team.id}>{team.name}</Option>)}
        </Select>
      </FormItem>
      <Popconfirm title='如果修改了负责的开发组，则原有开发组将不在有权限访问和维护此项目'
        onConfirm={onSubmit}
      >
        <Button type='primary'>确定</Button>
      </Popconfirm>
    </Form>
  );
};
TeamForm = Form.create()(TeamForm);

let MachinesForm = ({ companyMachines, groupId, machineIds, form, onUpdateMachines }) => {
  const { getFieldProps, getFieldValue } = form;

  const onSubmit = () => {
    onUpdateMachines(groupId, getFieldValue('machineIds'))
      .then(({ error }) => {
        if (!error) {
          message.success('更新成功');
        }
      });
  };

  return (
    <Form inline>
      <FormItem label='分配的机器：'>
        <Select multiple style={{ width: '700px' }} {...getFieldProps('machineIds', { initialValue: machineIds })}>
          {companyMachines.map((machine) => <Option key={machine.id} value={machine.id}>{machine.ip}</Option>)}
        </Select>
      </FormItem>
      <Popconfirm title='当移除已有机器时，并不会停止机器上正在运行的应用，机器也会暂时脱离控制，请确认后再操作'
        onConfirm={onSubmit}
      >
        <Button type='primary'>确定</Button>
      </Popconfirm>
    </Form>
  );
};
MachinesForm = Form.create()(MachinesForm);

const CompanyRunnableGroups = ({ fetching, runnableGroups, companyMachines, companyTeams, onAssign, onUpdateMachines }) => {
  return (
    <Panel spinner={fetching}>
      <div className='company-runnable-group-list'>
        {runnableGroups.map(({ id, name, desc, machineIds, teamId }) => {
          return (
            <div className='list-item' key={id}>
              <h3 className='group-name'>{name}</h3>
              <p className='group-desc'>{desc}</p>
              <TeamForm companyTeams={companyTeams} groupId={id} teamId={teamId} onAssign={onAssign}/>
              <MachinesForm companyMachines={companyMachines} groupId={id} machineIds={machineIds}
                onUpdateMachines={onUpdateMachines}/>
            </div>
          );
        })}
      </div>
    </Panel>
  );
};

export default CompanyRunnableGroups;
